<?php
/**
 * Access Controll List
 *
 * Defines the access controll list defined by database,
 * there are some dependencies added in the acl
 * GROUP_ID 1  fixed for guest user
 * GROUP_ID 99 fixed for administrator //you can change it at getAdminGroupId
 * remaining groups can be dynamically controlled from admin module
 *
 * @copyright 
 * @version   $Id: Acl.php 12 2011-04-09 08:58:51Z sandeep.manne@gmail.com $
 */

class Acl extends Core_Model
{
	/**
	 * Check whether access is allowed to group
	 * 
	 * @param int $groupId
	 * @param string $module
	 * @param string $controller
	 * @param string $action
	 */
	public static function isAllowed($groupId, $module, $controller, $action) 
	{
		return App::getDAO("acl", "Acl")->isAllowed($groupId, $module, $controller, $action);
	}
	
	/**
	 * Add access control list
	 * 
	 * @param int    $groupId
	 * @param string $module
	 * @param string $controller
	 * @param string $action
	 * @param int    $permission
	 * @throws Exception
	 */
	public static function addAcl($groupId, $module, $controller, $action, $permission)
	{
		if (Acl::isAdmin($groupId)) {
			throw new Exception("Cannot add any restriction to Admin", "001");
		}
		/* @var $aclDAO AclDAO */
		$aclDAO = App::getDAO("acl", "Acl");
		return $aclDAO->addAcl($groupId, $module, $controller, $action, $permission);
	}
	
	/**
	 * This is used to check whether the given group id belongs to admin or not
	 * @param $groupId
	 */
	public static function isAdmin($groupId){
		return $groupId == Acl::getAdminGroupId();
	}
	
	/**
	 * The only place where admin groupId is hardcoded
	 */
	public static function getAdminGroupId()
	{
		return 99;
	}
	
	/**
	 * Hardcoded guest groupId
	 */
	public static function getGuestGroupId()
	{
		return 1;
	}
	
	/**
	 * Update resource table to allow admin to choose 
	 * acl dynamically
	 */
	public static function updateModuleResource()
	{
		require_once 'Core/Module.php';
		$modules = Core_Module::getAvailableModules();
		/* @var $resourceModuleDAO ResourceModuleDAO */
		$resourceModuleDAO = App::getDAO("acl", "ResourceModule");
		foreach ($modules as $module) {
			$resourceModuleDAO->addModule($module);
		}
		return $resourceModuleDAO->getAllModules();
	}
	
	/**
	 * Update resource table to allow admin to choose 
	 * acl dynamically
	 */
	public static function updateControllerResource()
	{
		require_once 'Core/Module.php';
		$modules = Core_Module::getAvailableModules();
		/* @var $resourceModuleDAO ResourceModuleDAO */
		$resourceModuleDAO = App::getDAO("acl", "ResourceModule");
		/* @var $resourceControllerDAO ResourceControllerDAO */
		$resourceControllerDAO = App::getDAO("acl", "ResourceController");
		foreach ($modules as $module) {
			$module      = $resourceModuleDAO->getModuleByName($module);
			$controllers = Core_Module::getControllers($module["module_name"]);
			foreach($controllers as $controller) {
				$resourceControllerDAO->addController($module['module_id'], $controller);
			}
		}
	}
}